const Router = require('koa-router');
const db = require('../../db');
const moment = require('moment');

const router = new Router({ prefix: '/api/admin' });

// 获取评价列表
router.get('/evaluations', async (ctx) => {
  try {
    const { keyword, startDate, endDate, teacherId } = ctx.query;
    
    let conditions = [];
    let params = [];
    
    // 添加教师ID筛选条件
    if (teacherId) {
      conditions.push('c.teacher_id = ?');
      params.push(teacherId);
    }
    
    if (keyword) {
      conditions.push('(c.title LIKE ? OR b.contact_name LIKE ?)');
      params.push(`%${keyword}%`, `%${keyword}%`);
    }
    
    if (startDate && endDate) {
      conditions.push('DATE(cc.created_at) BETWEEN ? AND ?');
      params.push(startDate, endDate);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    const sql = `
      SELECT 
        b.id,
        b.contact_name,
        b.contact_phone,
        b.booking_date,
        b.time_slot,
        c.title as course_title,
        cc.rating,
        cc.content as comment,
        cc.created_at as rating_time,
        u.avatar
      FROM course_comments cc
      INNER JOIN bookings b ON cc.booking_id = b.id
      INNER JOIN courses c ON cc.course_id = c.id
      INNER JOIN users u ON b.user_id = u.id
      ${whereClause}
      ORDER BY cc.created_at DESC
    `;
    
    console.log('执行的SQL语句：', sql);
    console.log('SQL参数：', params);
    
    const result = await db.query(sql, params);
    
    // 格式化日期并过滤掉 null 值
    const data = result
      .filter(item => item.id != null) // 过滤掉 id 为 null 的记录
      .map(item => ({
        ...item,
        booking_date: moment(item.booking_date).format('YYYY-MM-DD'),
        rating_time: moment(item.rating_time).format('YYYY-MM-DD HH:mm:ss')
      }));
    
    ctx.body = {
      code: 0,
      data,
      msg: 'success'
    };
  } catch (error) {
    console.error('获取评价列表失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

module.exports = router; 